<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="影视ID" prop="movieId">
        <el-input
          v-model="queryParams.movieId"
          placeholder="请输入影视ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="视频标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入视频标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="视频类型" prop="videoType">
        <el-select v-model="queryParams.videoType" placeholder="请选择视频类型" clearable>
          <el-option label="正片" value="main" />
          <el-option label="预告片" value="trailer" />
          <el-option label="花絮" value="extra" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['movie:video:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['movie:video:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['movie:video:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['movie:video:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="视频ID" align="center" prop="videoId" width="80" />
      <el-table-column label="影视ID" align="center" prop="movieId" width="80" />
      <el-table-column label="视频标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="集数/季数" align="center" prop="episodeNumber" width="100">
        <template #default="scope">
          <span v-if="scope.row.seasonNumber">S{{ scope.row.seasonNumber }}</span>
          <span v-if="scope.row.episodeNumber">E{{ scope.row.episodeNumber }}</span>
          <span v-if="!scope.row.seasonNumber && !scope.row.episodeNumber">-</span>
        </template>
      </el-table-column>
      <el-table-column label="视频类型" align="center" prop="videoType" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.videoType === 'main'" type="primary">正片</el-tag>
          <el-tag v-else-if="scope.row.videoType === 'trailer'" type="warning">预告片</el-tag>
          <el-tag v-else-if="scope.row.videoType === 'extra'" type="info">花絮</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="duration" width="80">
        <template #default="scope">
          {{ formatDuration(scope.row.duration) }}
        </template>
      </el-table-column>
      <el-table-column label="播放量" align="center" prop="playCount" width="100" />

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handlePreview(scope.row)">预览</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['movie:video:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['movie:video:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改视频对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="videoRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="影视ID" prop="movieId">
              <el-input-number v-model="form.movieId" :min="1" placeholder="请输入影视ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频类型" prop="videoType">
              <el-select v-model="form.videoType" placeholder="请选择视频类型">
                <el-option label="正片" value="main" />
                <el-option label="预告片" value="trailer" />
                <el-option label="花絮" value="extra" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="视频标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入视频标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="季数" prop="seasonNumber">
              <el-input-number v-model="form.seasonNumber" :min="0" placeholder="请输入季数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="集数" prop="episodeNumber">
              <el-input-number v-model="form.episodeNumber" :min="0" placeholder="请输入集数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="视频URL" prop="videoUrl">
              <el-input v-model="form.videoUrl" placeholder="请输入视频URL" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="时长(秒)" prop="duration">
              <el-input-number v-model="form.duration" :min="0" placeholder="请输入时长" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件大小" prop="fileSize">
              <el-input v-model="form.fileSize" placeholder="请输入文件大小(MB)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分辨率" prop="resolution">
              <el-select v-model="form.resolution" placeholder="请选择分辨率">
                <el-option label="480P" value="480P" />
                <el-option label="720P" value="720P" />
                <el-option label="1080P" value="1080P" />
                <el-option label="2K" value="2K" />
                <el-option label="4K" value="4K" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 视频预览对话框 -->
    <el-dialog title="视频预览" v-model="previewOpen" width="800px" append-to-body>
      <div v-if="previewUrl" style="text-align: center;">
        <video
          :src="previewUrl"
          controls
          style="max-width: 100%; max-height: 500px;"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
      <div v-else style="text-align: center; padding: 50px;">
        <el-empty description="暂无视频" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="MovieVideo">
import { listVideo, getVideo, delVideo, addVideo, updateVideo } from "@/api/movie/video";
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';

const { proxy } = getCurrentInstance();

const videoList = ref([]);
const open = ref(false);
const previewOpen = ref(false);
const previewUrl = ref("");
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 从URL参数获取movieId
const route = proxy.$route;
const movieIdFromRoute = route.query?.movieId;

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    movieId: movieIdFromRoute || null,
    title: null,
    videoType: null
  },
  rules: {
    movieId: [
      { required: true, message: "影视ID不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "视频标题不能为空", trigger: "blur" }
    ],
    videoType: [
      { required: true, message: "视频类型不能为空", trigger: "change" }
    ],
    videoUrl: [
      { required: true, message: "视频URL不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 格式化时长 */
function formatDuration(seconds) {
  if (!seconds) return '-';
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  if (h > 0) {
    return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  }
  return `${m}:${String(s).padStart(2, '0')}`;
}

/** 查询视频列表 */
function getList() {
  loading.value = true;
  listVideo(queryParams.value).then(response => {
    videoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    videoId: null,
    movieId: movieIdFromRoute || null,
    title: null,
    seasonNumber: null,
    episodeNumber: null,
    videoType: 'main',
    videoUrl: null,
    duration: null,
    fileSize: null,
    resolution: '1080P',
    playCount: 0,
    status: "0"
  };
  proxy.resetForm("videoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.movieId = movieIdFromRoute || null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.videoId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加视频";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _videoId = row.videoId || ids.value
  getVideo(_videoId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改视频";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["videoRef"].validate(valid => {
    if (valid) {
      if (form.value.videoId != null) {
        updateVideo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVideo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _videoIds = row.videoId || ids.value;
  proxy.$modal.confirm('是否确认删除视频编号为"' + _videoIds + '"的数据项？').then(function() {
    return delVideo(_videoIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('movie/video/export', {
    ...queryParams.value
  }, `movie_video_${new Date().getTime()}.xlsx`)
}



// 预览视频
function handlePreview(row) {
  previewUrl.value = row.videoUrl;
  previewOpen.value = true;
}

getList();
</script>
